package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.BaseParams;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.entity.rDistributionMain;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.HashMap;
import org.json.JSONException;

/**
 * 配送货详情
 *
 * @author wu
 */
@SuppressWarnings("DanglingJavadoc") public class DeliveryDetailFragment
    extends DeliveryBaseFragment {

  public static final String EXTRA_VALUE = "com.isunland.managesystem.ui.EXTRA_VALUE";
  rDistributionMain mDeliveryDetail;

  public static Fragment newInstance(rDistributionMain detail) {
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_VALUE, detail);
    DeliveryDetailFragment fragment = new DeliveryDetailFragment();
    fragment.setArguments(bundle);
    return fragment;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTitleCustom(R.string.deliveryDetail);
    mDeliveryDetail = (rDistributionMain) getArguments().getSerializable(EXTRA_VALUE);
    if (mDeliveryDetail != null) {
      mDataStatus = mDeliveryDetail.getDataStatus();
      mId = mDeliveryDetail.getId();
      mRunId = mDeliveryDetail.getRunId();
      mOrderNumber = mDeliveryDetail.getMoutbillName();
      mContractCode = mDeliveryDetail.getContractName();
      mCustomerName = mDeliveryDetail.getCustomerName();
      mStaffName = mDeliveryDetail.getDistributionStaffName();
      //mMainGoods = mDeliveryDetail.getMainGoods().trim();
      mAddressName = mDeliveryDetail.getDistributionAddress();
      mLogText = mDeliveryDetail.getDistributionLog();
      mIfThirdLogistics = mDeliveryDetail.getIfThirdlogistics();
      mDeliveryFee = mDeliveryDetail.getDistributionCost();
      mIfPay = mDeliveryDetail.getIfPay();
      mLogisticsName = mDeliveryDetail.getLogisticsCompany();
      mLogisticsNum = mDeliveryDetail.getLogisticsNumber();
      mDataStatus = mDeliveryDetail.getDataStatus();
      mOrderId = mDeliveryDetail.getMoutbillId();
      mCustomerId = mDeliveryDetail.getCustomerId();
      regStaffId = mDeliveryDetail.getRegStaffId();
      LogUtil.i("mCustomerName===" + mCustomerName);
    }
  }

  public void initView() {
    if (!TextUtils.isEmpty(mOrderNumber)) {
      mOrderNum_addEditDelivery.setText(mOrderNumber);
    }
    if (!TextUtils.isEmpty(mContractCode)) {
      mRelativeContract_addEditDelivery.setText(mContractCode);
    }
    if (!TextUtils.isEmpty(mCustomerName)) {
      mCustomerNameDelivery_addEditDelivery.setText(mCustomerName);
    }
    if (!TextUtils.isEmpty(mStaffName)) {
      mDeliveryPerson_addEditDelivery.setText(mStaffName);
    }
    //if (!TextUtils.isEmpty(mMainGoods)) {
    //  mMainGoods_addEditDelivery.setText(mMainGoods);
    //}
    if (!TextUtils.isEmpty(mAddressName)) {
      mDeliveryAddress_addEditDelivery.setText(mAddressName);
    }
    if (!TextUtils.isEmpty(mLogText)) {
      mDeliveryText_addEditDelivery.setText(mLogText);
    }
    if (!TextUtils.isEmpty(mIfThirdLogistics)) {
      if (VALUE_TRUE.equalsIgnoreCase(mIfThirdLogistics)) {
        mFfThirdLogistics_addEditDelivery.setText(R.string.isTrue);
        mLogisticsCompany_addEditDelivery.setEnabled(true);
        mLogisticsNum_addEditDelivery.setEnabled(true);
      } else if (VALUE_FALSE.equalsIgnoreCase(mIfThirdLogistics)) {
        mFfThirdLogistics_addEditDelivery.setText(R.string.isFalse);
        mLogisticsCompany_addEditDelivery.setEnabled(false);
        mLogisticsNum_addEditDelivery.setEnabled(false);
      }
    }
    if (!TextUtils.isEmpty(mDeliveryFee)) {
      mDeliveryFee_addEditDelivery.setText(mDeliveryFee);
    }

    if (!TextUtils.isEmpty(mIfPay)) {
      if (VALUE_TRUE.equalsIgnoreCase(mIfPay)) {
        mFfPay_addEditDelivery.setText(R.string.isTrue);
      } else if (VALUE_FALSE.equalsIgnoreCase(mIfPay)) {
        mFfPay_addEditDelivery.setText(R.string.isFalse);
      }
    }
    if (!TextUtils.isEmpty(mLogisticsName)) {
      mLogisticsCompany_addEditDelivery.setText(mLogisticsName);
    }
    if (!TextUtils.isEmpty(mLogisticsNum)) {
      mLogisticsNum_addEditDelivery.setText(mLogisticsNum);
    }
    mDataState_addEditDelivery.setText(mDeliveryDetail == null ? ""
        : mDeliveryDetail.getStatusConfig(mDeliveryDetail.getDataStatus()).getStatusName());
    //if (!TextUtils.isEmpty(mDataStatus)) {
    //  if ("new".equalsIgnoreCase(mDataStatus)) {
    //    mDataState_addEditDelivery.setText(R.string.draft);
    //  } else if ("waitCheck".equalsIgnoreCase(mDataStatus)) {
    //    mDataState_addEditDelivery.setText(R.string.checking);
    //    mAddress_addEditDelivery.setVisibility(View.GONE);
    //    setEnableFalse();
    //  } else if ("checkPass".equalsIgnoreCase(mDataStatus)) {
    //    mDataState_addEditDelivery.setText(R.string.checkapprovve);
    //    mLl_logistiDetail_addEditDelivery.setVisibility(View.VISIBLE);
    //    mLogisticsDetail_addEditDelivery.setOnClickListener(this);
    //    mAddress_addEditDelivery.setVisibility(View.GONE);
    //    setEnableFalse();
    //  } else if ("abort".equalsIgnoreCase(mDataStatus)) {
    //    mDataState_addEditDelivery.setText(R.string.stopup);
    //  }
    //}
    if (!TextUtils.isEmpty(mDeliveryDetail.getRegStaffName())) {
      mRegister_addEditDelivery.setText(mDeliveryDetail.getRegStaffName());
    }
    /** 手机端只不再处理修改操作,所以全部禁用*/
    setEnableFalse();
  }

  /**
   * 审核通过和审核中状态下不能进行操作
   */
  private void setEnableFalse() {
    mOrderNum_addEditDelivery.setEnabled(false);
    mRelativeContract_addEditDelivery.setEnabled(false);
    mCustomerNameDelivery_addEditDelivery.setEnabled(false);
    mDeliveryPerson_addEditDelivery.setEnabled(false);
    mMainGoods_addEditDelivery.setEnabled(false);
    mDeliveryAddress_addEditDelivery.setEnabled(false);
    mDeliveryText_addEditDelivery.setEnabled(false);
    mLogisticsNum_addEditDelivery.setEnabled(false);
    mDeliveryFee_addEditDelivery.setEnabled(false);
    mFfPay_addEditDelivery.setEnabled(false);
    mLogisticsCompany_addEditDelivery.setEnabled(false);
    mLogisticsNum_addEditDelivery.setEnabled(false);
    mRegister_addEditDelivery.setEnabled(false);
    mFfThirdLogistics_addEditDelivery.setEnabled(false);
    mAddress_addEditDelivery.setEnabled(false);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    //手机端不处理修改操作.
    //if ("new".equalsIgnoreCase(mDataStatus) || "abort".equalsIgnoreCase(mDataStatus)) {
    //  inflater.inflate(R.menu.menu_save_submit_delete, menu);
    //} else if ("waitCheck".equalsIgnoreCase(mDataStatus)) {
    //  inflater.inflate(R.menu.menu_stop, menu);
    //}
    menu.add("签收").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
      @Override public boolean onMenuItemClick(MenuItem item) {
        SignReceiveFragment.newInstance(DeliveryDetailFragment.this, mDeliveryDetail);
        return true;
      }
    });
    menu.add("配送签到").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
      @Override public boolean onMenuItemClick(MenuItem item) {
        BaseVolleyActivity.newInstance(DeliveryDetailFragment.this, SignDeliveryPagerActivity.class,
            new BaseParams<>().setItem(mDeliveryDetail), DeliveryListFragment.REQUEST_UPDATE);
        return false;
      }
    });
    menu.add("发货清单").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
      @Override public boolean onMenuItemClick(MenuItem item) {
        BaseVolleyActivity.newInstance(DeliveryDetailFragment.this, ShippingListActivity.class,
            new BaseParams<>().setItem(mDeliveryDetail), 0);
        return false;
      }
    });
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    AlertDialog.Builder dialog;
    switch (item.getItemId()) {
      /**
       * 响应返回按钮
       */
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;
      // 保存
      case R.id.menu_item_save:
        // 进行非空判断，配送人、主要物品和发货地址不能为空
        if (TextUtils.isEmpty(mDeliveryPerson_addEditDelivery.getText().toString())) {
          MyUtils.show(getActivity(), R.string.chooseDeliveryPer);
        } else if (TextUtils.isEmpty(mMainGoods_addEditDelivery.getText().toString())) {
          MyUtils.show(getActivity(), R.string.chooseMainGoods);
        } else if (TextUtils.isEmpty(mDeliveryAddress_addEditDelivery.getText().toString())) {
          MyUtils.show(getActivity(), R.string.chooseDeliveryAdd);
        } else {
          // 只有草稿和终止的可以修改
          if ("new".equalsIgnoreCase(mDataStatus) || "abort".equalsIgnoreCase(mDataStatus)) {
            dialog = new AlertDialog.Builder(getActivity());
            dialog.setTitle(R.string.restart_title);
            dialog.setMessage(R.string.ifSureSave);
            dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

              @Override public void onClick(DialogInterface dialog, int which) {
                volleyPostSave();
              }
            });

            dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

              @Override public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
              }
            });
            dialog.create().show();
          } else {
            ToastUtil.show(R.string.deleteLimit);
          }
        }
        break;
      // 删除
      case R.id.menu_item_delete:
        dialog = new AlertDialog.Builder(getActivity());
        dialog.setTitle(R.string.restart_title);
        dialog.setMessage(R.string.deleteMind);
        dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

          @Override public void onClick(DialogInterface dialog, int which) {
            vollyPostDelete();
          }
        });

        dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

          @Override public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
          }
        });
        dialog.create().show();
        break;

      // 终止流程
      case R.id.menu_item_stop:
        dialog = new AlertDialog.Builder(getActivity());
        dialog.setTitle(R.string.restart_title);
        dialog.setMessage(R.string.ifSureStop);
        dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

          @Override public void onClick(DialogInterface dialog, int which) {
            volleyPostInterrupt();
          }
        });

        dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

          @Override public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
          }
        });
        dialog.create().show();
        break;

      // 启动流程
      case R.id.menu_item_submit:

        if (TextUtils.isEmpty(mDeliveryPerson_addEditDelivery.getText().toString())) {
          MyUtils.show(getActivity(), R.string.chooseDeliveryPer);
        } else if (TextUtils.isEmpty(mMainGoods_addEditDelivery.getText().toString())) {
          MyUtils.show(getActivity(), R.string.chooseMainGoods);
        } else if (TextUtils.isEmpty(mDeliveryAddress_addEditDelivery.getText().toString())) {
          MyUtils.show(getActivity(), R.string.chooseDeliveryAdd);
        } else {
          dialog = new AlertDialog.Builder(getActivity());
          dialog.setTitle(R.string.restart_title);
          dialog.setMessage(R.string.ifSureStart);
          dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

            @Override public void onClick(DialogInterface dialog, int which) {
              volleyPostStart();
            }
          });

          dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

            @Override public void onClick(DialogInterface dialog, int which) {
              dialog.dismiss();
            }
          });
          dialog.create().show();
        }
        break;
      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  /**
   * 启动流程
   */
  protected void volleyPostStart() {
    MyUtils.showDialogLoading(getActivity(), R.string.loadingStart);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DELIVERY_RUN);
    HashMap<String, String> params = getparams();
    params.put("dataStatus", "waitCheck");
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        try {
          SuccessMessage message = new Gson().fromJson(arg0, SuccessMessage.class);
          String result = message.getResult();
          String messages = message.getMessage();
          if (SuccessMessage.SUCCESS.equalsIgnoreCase(result)) {
            ToastUtil.show(R.string.startFolwSuccess);
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          } else {
            ToastUtil.show(messages);
          }
        } catch (Exception e) {
          MyUtils.show(getActivity(), R.string.startFolwFail);
          LogUtil.e("startError", e);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.startFolwFail);
      }
    });
  }

  /**
   * 保存
   */
  private void volleyPostSave() {
    MyUtils.showDialogLoading(getActivity(), R.string.loadingSave);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DELIVERT_SAVE);
    HashMap<String, String> params = getparams();
    // 如果是终止状态，修改后仍为终止状态
    if ("abort".equalsIgnoreCase(mDataStatus)) {
      params.put("dataStatus", "abort");
    }
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
        String resutl = success.getResult();
        if (SuccessMessage.SUCCESS.equalsIgnoreCase(resutl)) {
          MyUtils.show(getActivity(), R.string.save_success);
          MyUtils.dismissDialog();
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }

        if (SuccessMessage.FAILURE.equalsIgnoreCase(resutl)) {
          MyUtils.show(getActivity(), R.string.save_failure);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.save_failure);
      }
    });

    LogUtil.i("saveparams=====" + params);
  }

  /**
   * 终止流程
   */
  private void volleyPostInterrupt() {
    MyUtils.showDialogLoading(getActivity(), R.string.interrupting);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_TASK_STOP);
    HashMap<String, String> params = new HashMap<>();
    if (mRunId != null && !("".equalsIgnoreCase(mRunId))) {
      params.put("runId", mRunId);

      mActivity.volleyPost(url, params, new VolleyResponse() {

        @Override public void onVolleyResponse(String arg0) throws JSONException {
          MyUtils.dismissDialog();
          try {

            SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);
            String successType = successsMessage.getResult();
            if (successType.equals("1")) {
              ToastUtil.show(R.string.interruptSuccess);
              getActivity().setResult(Activity.RESULT_OK);
              getActivity().finish();
            } else {
              MyUtils.show(getActivity(), R.string.interruptFail);
            }
          } catch (Exception e) {
            LogUtil.e("interruptError", e);
            MyUtils.show(getActivity(), R.string.interruptFail);
          }
        }

        @Override public void onVolleyError(VolleyError arg0) {
          LogUtil.e("VolleyError", arg0);
          ToastUtil.show(R.string.failure_operation);
        }
      });
    }
  }

  /**
   * 删除
   */
  private void vollyPostDelete() {
    MyUtils.showDialogLoading(getActivity(), R.string.deleting);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DELIVERY_DELETE);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mId);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
        String resutl = success.getResult();
        String message = success.getMessage();
        if (SuccessMessage.SUCCESS.equalsIgnoreCase(resutl)) {
          ToastUtil.show(message);
          MyUtils.dismissDialog();
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }

        if (SuccessMessage.FAILURE.equalsIgnoreCase(resutl)) {
          MyUtils.show(getActivity(), message);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        MyUtils.show(getActivity(), R.string.deleteFail);
        LogUtil.e("arg0===" + arg0);
      }
    });
  }

  /**
   * 保存时的参数保存到hashmap
   *
   * @return params
   */
  public HashMap<String, String> getparams() {
    String trues = getString(R.string.isTrue);
    String falses = getString(R.string.isFalse);

    String mainGoods = mMainGoods_addEditDelivery.getText().toString().trim();
    String logisticsNum = mLogisticsNum_addEditDelivery.getText().toString().trim();
    String log = mDeliveryText_addEditDelivery.getText().toString().trim();
    String fee = mDeliveryFee_addEditDelivery.getText().toString().trim();
    String staffName = mDeliveryPerson_addEditDelivery.getText().toString().trim();
    String addressName = mDeliveryAddress_addEditDelivery.getText().toString().trim();
    String customer = mCustomerNameDelivery_addEditDelivery.getText().toString().trim();
    String thirdLogistics = mFfThirdLogistics_addEditDelivery.getText().toString().trim();
    String logisticsName = mLogisticsCompany_addEditDelivery.getText().toString().trim();
    String contractCode = mRelativeContract_addEditDelivery.getText().toString().trim();
    String orderNumber = mOrderNum_addEditDelivery.getText().toString().trim();
    String ifPay = mFfPay_addEditDelivery.getText().toString().trim();

    HashMap<String, String> params = new HashMap<>();
    params.put("id", mId);
    params.put("distributionStaffId", mjobNos); // 配送负责人工号
    params.put("distributionStaffName", staffName);// 配送负责人名称
    params.put("distributionAddress", addressName);// 配送地址
    params.put("mainGoods", mainGoods);// 配送货物
    if (!TextUtils.isEmpty(mCustomerId)) {
      params.put("customerId", mCustomerId); // 客户ID
    }
    if (!TextUtils.isEmpty(customer)) {
      params.put("customerName", customer); // 客户名称
    }
    if (!TextUtils.isEmpty(thirdLogistics)) {
      if (trues.equalsIgnoreCase(thirdLogistics)) {
        params.put("ifThirdlogistics", VALUE_TRUE);// 是否第三方物流
      } else if (falses.equalsIgnoreCase(thirdLogistics)) {
        params.put("ifThirdlogistics", VALUE_FALSE);// 是否第三方物流
      }
    }

    if (!TextUtils.isEmpty(logisticsName)) {
      params.put("logisticsCompany", logisticsName);// 物流公司名称
    }
    if (!TextUtils.isEmpty(logisticsNum)) {
      params.put("logisticsNumber", logisticsNum);// 物流单号
    }

    if (!TextUtils.isEmpty(log)) {
      params.put("distributionLog", log);// 配送日志
    }

    if (!TextUtils.isEmpty(mContractId)) {
      params.put("contractId", mContractId);// 关联销售合同ID
    }
    if (!TextUtils.isEmpty(contractCode)) {
      params.put("contractName", contractCode);// 关联合同编号
    }

    if (!TextUtils.isEmpty(mOrderId)) {
      params.put("moutbillId", mOrderId); // 关联出库单ID
    }
    if (!TextUtils.isEmpty(orderNumber)) {
      params.put("moutbillName", orderNumber); // 关联出库单编号
    }
    if (!TextUtils.isEmpty(fee)) {
      params.put("distributionCost", fee);// 配送费
    }

    if (!TextUtils.isEmpty(ifPay)) {
      if (trues.equalsIgnoreCase(ifPay)) {
        params.put("ifPay", VALUE_TRUE);// 是否支付
      } else if (falses.equalsIgnoreCase(ifPay)) {
        params.put("ifPay", VALUE_FALSE);// 是否支付
      }
    }
    return params;
  }
}
